const path = require("path");

const { normalizePath } = require("../utils");

async function createPluginContainer({ root, plugins }) {
  class PluginContext {
    async resolve(importee, importer) {
      return await container.resolveId(importee, importer);
    }
  }

  const container = {
    async resolveId(importee, importer) {
      const ctx = new PluginContext();
      let resolveId = importee;

      for (const plugin of plugins) {
        if (!plugin.resolveId) continue;

        const result = await plugin.resolveId.call(ctx, importee, importer);

        if (result) {
          resolveId = result.id || result;
          break; // 只要有插件返回 resolvedId， 就遍历结束
        }
      }

      return {
        id: normalizePath(resolveId),
      };
    },
    async load(id) {
      console.log("<<<<<<<<<<<,load");
      const ctx = new PluginContext();

      for (const plugin of plugins) {
        if (!plugin.load) continue;

        const result = await plugin.load.call(ctx, id);
        if (result) {
          return result;
        }
      }

      return null;
    },
    async transform(code, id) {
      console.log("<<<<<<<<<<<,transform");
      const ctx = new PluginContext();

      for (const plugin of plugins) {
        if (!plugin.transform) continue;

        const result = await plugin.transform.call(ctx, code, id);
        if (!result) {
          continue;
        }
        code = result.code || result;
      }

      return { code };
    },
  };

  return container;
}

module.exports = {
  createPluginContainer,
};
